package core;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;

/**
 *
 * @author Sasa
 */
public class Client implements Runnable {

    public Socket socket;
    public BufferedReader in;
    public DataOutputStream out;
    public Boolean loggeded = false;

    public Client(Socket socket) throws Exception {
        super();
        this.socket = socket;
        this.in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
        //this.out = new BufferedWriter(new OutputStreamWriter(this.socket.getOutputStream()));
        this.out = new DataOutputStream(this.socket.getOutputStream());
    }

    public void run() {
        try {
            // start controller
            this.controller();
        } catch(Exception e) {
            System.out.println(e);
        }
    }

    public void controller() throws Exception {
        String line;
        String[] params;

        while((line = this.in.readLine()) != null) {
            params = line.split("#");
            // Komande
            if(params[0].equals("LOGIN")) {
                sendResponse(login(params[1], params[2]));
            } else if(params[0].equals("TASKS")) {
                sendFile(tasks(params[1]));
            } else if(params[0].equals("COMPLETE")) {
                sendResponse(completedTask(params[1]));
            } else {
                sendResponse("UNKNOWN");
            }
        }
    }
    
    public String login(String username, String password) {
        
        return "OK";
    }

    public String completedTask(String taskId) {

        return "OK";
    }

    public File tasks(String userId) {

        return new File("xmls/tasks-" + userId + ".xml");
    }

    public Boolean sendFile(File file) throws Exception {
        byte[] bytes = new byte[(int)file.length()];
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
        bis.read(bytes,0,bytes.length);

        this.out.write(bytes);
        this.out.flush();
        return true;
    }

    public Boolean sendResponse(String msg) throws Exception {
        this.out.writeBytes(msg + "\n");
        this.out.flush();
        return true;
    }
}